<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * emails
  id (key)
  [user_id (index), email (unique)] (unique)
  timestamp (index)
 */

function add_email($user_id, $email) {
    if (!$user_id || strlen($email) <= 0)
        return FALSE;
    $timestamp = time();
    $query = "INSERT INTO emails (user_id, email, timestamp)
                VALUES ('$user_id', '$email', '$timestamp')
                ON DUPLICATE KEY UPDATE user_id = '$user_id', timestamp = '$timestamp'";
    return safe_insert_query($query);
}

function remove_email($user_id, $email) {
    if (!$user_id || strlen($email) <= 0)
        return FALSE;
    $timestamp = time();
    $query = "UPDATE emails SET user_id = '0', timestamp = '$timestamp'
                WHERE email = '$email'";
    return safe_update_query($query);
}

function get_user_id_by_email($email) {
    $query = "SELECT user_id FROM emails WHERE email = '$email' LIMIT 0, 1";
    $result = safe_select_query($query);
    return $result[0]->user_id;
}

function get_existed_user_by_email($email) {
    $query = "SELECT user_id FROM emails WHERE email = '$email' LIMIT 0, 1";
    $result = safe_select_query($query);
    if (empty($result)) {
        return FALSE;
    }
    return $result[0]->user_id;
}

function get_emails_of($user_id) {
    $query = "SELECT email FROM emails WHERE user_id = '$user_id'";
    return safe_select_query($query);
}

function suggest_whiteboard_follows_by_emails($user_id, $emails) {
    if (!is_array($emails) || count($emails) <= 0) {
        return array();
    }
    $email_list = "('token'";
    foreach ($emails as $email) {
        $email_list .= ", '$email'";
    }
    $email_list .= ")";
    $query = "SELECT user_id 
                FROM emails 
                WHERE email IN $email_list
                AND user_id NOT IN (SELECT follow_id FROM whiteboard_follows WHERE user_id = '$user_id')";

    return safe_select_query($query);
}

?>
